﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ConfigurationManagement.Administration.Data;
using ConfigurationManagement.Data;
using System.ComponentModel;

namespace ConfigurationManagement.Administration.UI
{
    public partial class ManageSolutionDictionaryValuesForm : Form
    {
        private readonly ConfigurationManagementDataContext _db = new ConfigurationManagementDataContext();
        private Project _selectedProject;
        private Solution _selectedSolution;

        public ManageSolutionDictionaryValuesForm()
        {
            InitializeComponent();
        }

        private void SolutionsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (SolutionsComboBox.SelectedIndex < 0) return;
            Save();
            _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
            LoadDictionary();
        }

        private void ProjectsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProjectsComboBox.SelectedIndex < 0) return;
            Save();
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void ManageSolutionDictionaryValuesFormLoad(object sender, EventArgs e)
        {
            SettingValuesDataGridView.AutoGenerateColumns = true;
            LoadProjects();
        }

        private void Save()
        {
            _db.SubmitChanges();
        }

        private void LoadProjects()
        {
            ProjectsComboBox.DisplayMember = "ProjectName";
            ProjectsComboBox.ValueMember = "ProjectID";            
            ProjectsComboBox.DataSource = _db.Projects.OrderBy(x => x.ProjectName);
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void LoadSolutions()
        {
            if (_selectedProject == null) return;
            SolutionsComboBox.DisplayMember = "SolutionName";
            SolutionsComboBox.ValueMember = "SolutionID";
            var items = new List<Solution>(_selectedProject.Solutions.OrderBy(x => x.SolutionName));
            SolutionsComboBox.DataSource = items;
            _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
            LoadDictionary();
        }

        /// <summary>
        /// </summary>
        private void LoadDictionary()
        {
            if (_selectedProject == null || _selectedSolution == null)
                return;
            if(_selectedSolution.SolutionSettings.Count == 0)
            {
                SettingValuesDataGridView.DataSource = null;
                MessageBox.Show(@"The selected solution has no settings in its dictionary.  Please add some before adding per environment settings",
                    @"No settings");
                return;
            }
            var ds = CrossTab.GetCrossTabData(_selectedProject.ProjectID, _selectedSolution.SolutionID);
            if (ds.Tables.Count > 0)
                SettingValuesDataGridView.DataSource = ds.Tables[0];

            SettingValuesDataGridView.Sort(SettingValuesDataGridView.Columns[0], ListSortDirection.Ascending);
        }

        private void SettingValuesDataGridViewCellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var column = SettingValuesDataGridView.Columns[e.ColumnIndex];
            var row = SettingValuesDataGridView.Rows[e.RowIndex];
            var cell = row.Cells[e.ColumnIndex];
            var tagCell = row.Cells[0];
            
            var solutionSetting =
                _selectedSolution.SolutionSettings.Single(p => p.SettingTag == (string) tagCell.Value);
           
            var environmentId =
                _selectedProject.Environments.Single(p => p.EnvironmentName == column.HeaderText).EnvironmentID;

            var count =
                _db.SettingValues.Count(
                    p => p.SolutionSettingID == solutionSetting.SolutionSettingID && p.EnvironmentID == environmentId);
            
            if (count == 0)
            {
                if (cell.Value != DBNull.Value)
                {
                    var settingValue = new SettingValue
                                           {
                                               EnvironmentID = environmentId,
                                               SolutionSettingID = solutionSetting.SolutionSettingID,
                                               SettingValue1 = (string) cell.Value
                                           };
                    solutionSetting.SettingValues.Add(settingValue);
                }
            }
            else
            {
                var settingValue =
                    _db.SettingValues.Single(
                        p =>
                        p.EnvironmentID == environmentId && p.SolutionSettingID == solutionSetting.SolutionSettingID);
                settingValue.SettingValue1 = cell.Value == DBNull.Value ? string.Empty : (string) cell.Value;
            }
            _db.SubmitChanges();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}